<template>
  <!-- 报告单元 -->
  <div id="CAUser">
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="50">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input v-model="form.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @keyup="keyupEnter" @clear="findCAUserList" @search-click="handleSearch(form)"></vxe-input>
              <vxe-select ref="refType" v-model="form.interfaceId" placeholder="请选择接口" style="width:30%;">
                <vxe-option v-for="intf in interfaceTypeList" :key="intf.id" :label="intf.interfaceName" :value="intf.id"></vxe-option>
              </vxe-select>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="showLoading" @click="findCAUserList"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="leftTable">
            <vxe-table ref="rptGroupTable" border="inner" align="left" class="mytable-scrollbar" :loading="showLoading" height="800" :data="cAUserList" :expand-config="{ expandAll: true, reserve: true }" @current-change="userRowClick" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                    isArrow: true,
                    isTab: true,
                    isEdit: false
                  }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30px" align="center"></vxe-column>
              <vxe-column field="seq" title="序号" width="35px" align="center"></vxe-column>
              <vxe-column field="username" title="用户名" width="120px"> </vxe-column>
              <vxe-column field="realname" title="真实姓名" width="120px"> </vxe-column>
              <vxe-column field="idCard" title="身份证号" min-width="200px"> </vxe-column>
              <vxe-column field="tel" title="手机号" min-width="130px">
              </vxe-column>
              <vxe-column field="caUserId" title="CA用户ID" min-width="200px"></vxe-column>
              <vxe-column field="activeCode" title="激活码" min-width="100px"></vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="50">
          <el-tabs type="border-card">
            <el-tab-pane label="基本信息">
              <!-- 右侧基本信息 -->
              <el-form ref="caUserForm" :model="form" :rules="formRules" style="margin-top:20px;" class="form-input-m" v-loading="showLoading" label-width="110px" inline-message>
                <el-form-item label="用户名" prop="username">
                  <el-input v-model="form.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="真实姓名" prop="realname">
                  <el-input v-model="form.realname" disabled></el-input>
                </el-form-item>

                <el-form-item label="手机号" prop="tel">
                  <el-input v-model="form.tel" placeholder="请输入手机号" clearable></el-input>
                </el-form-item>
                <el-form-item label="身份证号" prop="idCard">
                  <el-input v-model="form.idCard" placeholder="请输入身份证号" clearable></el-input>
                </el-form-item>
                <el-form-item label="CA用户ID" prop="caUserId">
                  <el-input v-model="form.caUserId" disabled></el-input>&nbsp;&nbsp;
                  <vxe-button @click="createCaUser('caUserForm')">生成CA用户</vxe-button>
                </el-form-item>
                <el-form-item label="CA签名图片" prop="signimg">
                  <img :src="form.signimg" style="width:200px;height:50px;" />
                </el-form-item>
                <el-form-item label="激活码" prop="activeCode">
                  <el-input v-model="form.activeCode" placeholder="请输入激活码" clearable></el-input>
                </el-form-item>
                <el-form-item label="激活二维码" prop="activeQrCode">
                  <div id="qrcode" class="qrcode"></div>
                </el-form-item>
                <el-form-item class="form-footer">
                  <template #default>
                    <el-button type="primary" v-loading="saveLoading" @click="save('caUserForm')">保存</el-button>
                    <el-button type="default" @click="resetForm(currentUser)">重置</el-button>
                  </template>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted, watch } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import { AppStore } from '@/stores/store';
import { VXETable, VxeFormPropTypes, VxeButtonEvents } from 'vxe-table';
import { isEmpty } from 'lodash';
import { Splitpanes, Pane } from 'splitpanes';
import QRCode from 'qrcodejs2-fix';

// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();

// 获取屏幕高度
let conHeight = ref((document.documentElement.clientHeight || document.body.clientHeight) - 148 + 'px');
// 获取屏幕宽度
let conWidth = ref(document.documentElement.clientWidth);
// 加载状态
let showLoading = ref(false); //左侧表格加载+上方刷新按钮+右侧表单+右侧详情
let saveLoading = ref(false); //保存
let rptGroupTable = ref(); //报告单元表格
let cAUserList: any = reactive([]); //报告单元列表数据

// 当前选中报告单元数据
let rptGroupInfo: any = reactive({
  id: '',
  rptGroupName: ''
});

// 模块对象
let modules: any = reactive([]);
let currentUser = reactive({}); //当前报告单元
let form = reactive({
  id: null,
  username: '',
  realname: '',
  tel: '',
  caUserId: '',
  idCard: '',
  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName,
  activeCode: '',
  activeQrCode: '',
  signimg: '',
  seq: 0,
  interfaceId: ''
});
let interfaceTypeList = reactive([]);

let defaultProps = {
  children: 'children',
  label: 'name'
};

let sltPurpose: any = ref({});

// 表单校验规则
const formRules = reactive<VxeFormPropTypes.Rules>({
  tel: [{ required: true, message: '请输入手机号' }],
  idCard: [{ required: true, message: '请输入身份证号' }]
});

let props = defineProps({
  systemId: String,
  moduleId: String,
  moduleSystemName: String
}) as any;
watch(
  () => props.systemId,
  (n, o) => {
    findInterfaceList();
  },
  {
    deep: true,
    immediate: true
  }
);
watch(
  () => props.moduleId,
  (newval, oldvbal) => {
    findInterfaceList();
  },
  {
    deep: true
  }
);

function findInterfaceList() {
  interfaceTypeList.length = 0;
  const url = '/api/sys/SysInterfaceCaUser/findInterfaceList';
  proxy.$http
    .get(url, { params: { systemId: props.systemId, moduleId: props.moduleId } })
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        interfaceTypeList.push(...res.data);
        form.interfaceId = res.data[0].id;
      }
      findCAUserList();
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

function createCaUser() {
  let $el = proxy.$refs.caUserForm;
  if (!$el) return;
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const url = '/public/user/getCaUserInfo';
    proxy.$http.get(url, { params: { tel: form.tel, idCard: form.idCard, username: form.username, realname: form.realname } }).then((res: any) => {
      if (res.data) {
        form.caUserId = res.data.userId;
        form.activeCode = res.data.activeCode;
        form.signimg = 'data:image/png;base64,' + res.data.signimg;
        form.activeQrCode = res.data.qrCode;
        document.getElementById('qrcode').innerHTML = '';
        proxy.$nextTick(() => {
          new QRCode(document.getElementById('qrcode'), {
            text: res.data.qrCode,
            width: 200,
            height: 200,
            colorDark: '#000000',
            colorLight: '#ffffff'
          });
        });
      }
    });
  });
}

function findCAUserList() {
  showLoading.value = true;
  cAUserList.length = 0;
  const url = '/api/sys/SysInterfaceCaUser/findInterfaceCaUserList';
  proxy.$http
    .get(url, { params: { interfaceId: form.interfaceId } })
    .then((res: any) => {
      cAUserList.push(...res.data);

      if (cAUserList.length > 0) {
        const kn = cAUserList.find((k) => k.id == sltPurpose.value.id);
        if (isEmpty(kn)) {
          rptGroupInfo.id = cAUserList[0].id;
          rptGroupInfo.rptGroupName = cAUserList[0].rptGroupName;
          userRowClick({ row: cAUserList[0] });
        } else {
          rptGroupInfo.id = kn.id;
          rptGroupInfo.rptGroupName = kn.rptGroupName;
          userRowClick({ row: kn });
        }
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
  //showLoading.value = true;
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    handleSearch(form);
  }
}

// 查询/刷新
function handleSearch(row: any) {
  showLoading.value = true;
  cAUserList.length = 0;
  const url = '/api/sys/SysInterfaceCaUser/findInterfaceCaUserList';
  proxy.$http
    .get(url, { params: { keyWords: row.searchValue, interfaceId: form.interfaceId } })
    .then((res: any) => {
      cAUserList.push(...res.data);
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      VxeMessage('查询刷新失败', VxeNotifyType.error);
    });
}

// 重置
function resetForm(row: any) {
  if (isEmpty(row)) {
    clearForm();
    return;
  }
  form.tel = '';
  form.caUserId = '';
  form.idCard = '';
  form.activeCode = '';
  form.signimg = '';
  form.activeQrCode = '';
  form.orgId = store.userInfo.orgId;
  form.orgName = store.userInfo.orgName;
  form.seq = cAUserList.length;
}

// 点击当前行// 行点击事件(需要调试)
function userRowClick({ row }: any) {
  if (isEmpty(row)) {
    currentUser = {} as any;
    return;
  }

  // let $Xtable = proxy.$refs.userTable;
  // $Xtable.setCurrentRow(row);
  currentUser = row;
  sltPurpose.value = row;
  (proxy.$refs.rptGroupTable as any).setCurrentRow(row);
  Object.assign(form, row);
  document.getElementById('qrcode').innerHTML = '';
  proxy.$nextTick(() => {
    new QRCode(document.getElementById('qrcode'), {
      text: row.activeQrCode,
      width: 200,
      height: 200,
      colorDark: '#000000',
      colorLight: '#ffffff'
    });
  });
  //getSysUserAuthdetailsByRoleIds();
}

// 保存
function save(formName: any) {
  let $el = proxy.$refs.caUserForm;
  if (!$el) return;
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    const $form = proxy.$refs.caUserForm;
    saveLoading.value = true;
    if ($form) {
      // 新增报告单元
      const url = '/api/sys/SysInterfaceCaUser/addSysInterfaceCaUser';
      proxy.$http
        .post(url, form)
        .then((res: any) => {
          VxeMessage('保存成功', VxeNotifyType.success);
          sltPurpose.value.id = res.data.id;
          findCAUserList();
        })
        .catch((err: any) => {
          VxeMessage('保存失败', VxeNotifyType.error);
          findCAUserList();
        });
      saveLoading.value = false;
    }
  });
}

// 清空右侧表单
function clearForm() {
  form.id = null;
  form.tel = '';
  form.caUserId = '';
  form.idCard = '';
  form.activeCode = '';
  form.signimg = '';
  form.activeQrCode = '';
}
</script>

<style lang="scss" scoped>
#CAUser {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);

    .splitpanes {
      background-color: $base-white;

      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }

      .tableBody {
        height: calc(100% - 40px);
      }

      .el-tabs {
        height: 100%;

        :deep(.el-tabs__content) {
          padding: 0;
          height: calc(100% - 39px);

          .el-tab-pane {
            height: 100%;
          }

          #pane-first {
            .el-form {
              padding: 20px;
            }
          }
        }
      }

      // 各个组件与右侧删除按钮的间距
      .vxe-checkbox {
        margin: 5px;
      }
    }
  }
}
</style>
